# -*- coding: utf-8 -*-
import sys
sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
from urllib.parse import urlencode
import requests
from common.helper import Helper

class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "平安上海医保账户重大疾病保险"
    # 生成产品信息
    def genProductInfo(self):
        plan = {
            # 年龄段
            "year":["16-25","26-30","31-35","36-40","41-45","46-50","51-55","56-60","61-65"],
            #性别
            "gender":["M","F"],
            # 社保
            "socialSec":["Y"],
            #保额
            "money":["100000","200000"],
            #交费类型
            "payType":["年交"],
            #保障期限
            "expire":["1年"]
        }
        for v in product(plan["year"],plan["gender"],plan["socialSec"],plan["money"],plan["payType"],plan["expire"]):
            self.mysql.cursor.execute( domain[self.name]["insert_sql"].format(
                v[0],v[1],v[2],v[3],v[4],v[5]
            ))
            self.mysql._conn.commit()
            print( domain[self.name]["insert_sql"].format(
                v[0],v[1],v[2],v[3],v[4],v[5]
            ) )

    #执行爬虫
    def requestJson(self,dt=None):

        age = str(2019-int(dt["year"].split("-")[0]))
        level = "01" if dt["money"] == "100000" else "02"
        data = {
            "c": "WI",
            "goodsId": "A000000064",
            "calcJson": '{"applyDate": "2020-03-09", "paymentModeCode": "5", "isRenewal": "N", "insurants": [{"seqno": "1", "birthDate": "'+age+'-3-9", "genderCode": "'+dt["gender"]+'", "socialSecurity": "Y", "isRenewal": "N","coverages": [{"productCode": "P129", "coverageAmount": "'+dt["money"]+'00", "coverageLevel": "'+level+'", "coverageUnits": 1,"periodMonth": "12", "periodDay": "0"}]}]}'
        }

        payload = urlencode( data ).replace("+","")
        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)
        if r.status_code == 200 and r.json()["status"] == "00":
            price = Helper.decimalParse( r.json()["totalPrem"])
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )
        else:
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            self.mysql.updateTask( data )
            print("\n/*更新产品价格失败:%d*/"%dt["id"])

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)

